package edu.sctu;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        DataBase dataBase = new DataBase();

        List<User> userList = dataBase.getUserList();


        for (User user:userList){
            if (user.getUserName().equals(userName)&&user.getPassword().equals(password)){
                HttpSession session = req.getSession();
                System.out.println("登录成功");
                session.setAttribute("isLogin","true");
                session.setAttribute("user",user);
                resp.sendRedirect("http://localhost:8080/userList");
            }
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.write("用户名或密码错误！");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }
}
